package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.controller.domain.News;
import com.ruoyi.web.controller.domain.Result;
import com.ruoyi.web.mapper.NewsMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
@RequestMapping("/news")
@Slf4j
public class newsController {




    @Autowired
    NewsMapper newsMapper;

//    @PostConstruct
//    public void inint(){
//         insertNews();
////       // getNewById(1l);
//    }

    @GetMapping("/{id}")
    public Result<News> getNewById(@PathVariable Long id){

        News xw = newsMapper.getById(id);
      //  String content = list.getContent();
        //log.info("查询结果:{}",content);
//        String sourceLink = "<p><a href=\"" + list.getSource() + "\">查看原文</a></p>";
//        content += sourceLink;
        return Result.success(xw);
    }


    @GetMapping("/list")
    public Result<List<News>> list(){

        List<News> list = newsMapper.list();
        log.info("list查询!");
        for (News news : list) {
            news.setContent("");
            //log.info("查询结果:{}",news);
        }

        return Result.success(list);
    }



    @Scheduled(cron = "0 0 8 * * ?")
    public void insertNews(){
       newsMapper.deleteNews();//删除前五条数据
        String url = "https://www.caas.cn/xwzx/mtxw/index.htm";
        ArrayList<String>  titles=new ArrayList<>();
        ArrayList<String>  images=new ArrayList<>();
        ArrayList<String>  urls=new ArrayList<>();
        ArrayList<String> contents=new ArrayList<>();
        ArrayList<News> news=new ArrayList<>();

        try {
            // 获取网页内容
            Document doc = Jsoup.connect(url).get();
            //System.out.println(doc);
            // 选择新闻列表项   .info_box
            Elements newsItems = doc.getElementsByClass("img_box");

            //Elements newsItems = doc.select(".item"); // 根据实际HTML结构调整选择器

            // 遍历前五条新闻
            int count = 0;
            String[] newUrl = new String[5];
            int newCount = 0;

            for (Element item : newsItems) {
                if (count >= 5) break; // 只取前五条

                // System.out.println(item);
                // 提取 a 标签的 href 链接
                Element linkElement = item.selectFirst("a");
                String hrefLink = linkElement.attr("href");
                String fullHrefLink = "https://www.caas.cn/xwzx/mtxw/" + hrefLink;

                // 提取 img 标签的 src 链接
                Element imgElement = item.selectFirst("img");
                String imgSrc = imgElement.attr("src");
                if (imgSrc.startsWith("../../")) {
                    imgSrc = imgSrc.substring(6); // 删除前缀 "../../"
                }
                String fullImgSrc = "https://www.caas.cn/" + imgSrc;
                urls.add(fullHrefLink);
                images.add(fullImgSrc);

//                System.out.println("a href link: " + fullHrefLink);
//                System.out.println("img src link: " + fullImgSrc);
//                System.out.println("--------------------------------------------------------------------------");
//
//                System.out.println("--------------------------------------------------------------------------");

                // 使用正则表达式提取链接
                String htmlContent = item.outerHtml();
                String regex = "<a\\s+href\\s*=\\s*\"([^\"]+)\"";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(htmlContent);

                while (matcher.find()) {
                    String extractedLink = matcher.group(1);
                    newUrl[newCount++] = "https://www.caas.cn/xwzx/mtxw/" + extractedLink;
                    // System.out.println("正则提取的链接: https://www.caas.cn/xwzx/mtxw/" + extractedLink);
                    break;
                }

                count++;
            }

            for (String s : newUrl) {
                if (s == null) continue; // 跳过未初始化的链接

                Document tempDoc = Jsoup.connect(s).get();
                //System.out.println(tempDoc);
                Element shareTitle = tempDoc.getElementById("shareTitle");
                Element gpCmsImg = tempDoc.selectFirst(".gpCmsImg img");

                titles.add(shareTitle.text());
                if (shareTitle != null) {

                    //   System.out.println("title: " + shareTitle.text());
                } else {
                    System.out.println("title: 未找到标题");
                }

//                if (gpCmsImg != null) {
//                    String imgSrc = gpCmsImg.attr("src");
//                    if (imgSrc.startsWith("../../")) {
//                        imgSrc = imgSrc.substring(6); // 删除前缀 "../../"
//                    }
//                    System.out.println("image src: " +"https://www.caas.cn/"+ imgSrc);
//                } else {
//                    System.out.println("image src: 未找到图片");
//                }

               // System.out.println("--------------------------------------------------------------------------");
            }

//            System.out.println("--------------------------------------------------------------------------");
//
//            System.out.println("--------------------------------------------------------------------------");

            for (String s : urls) {
                doc=Jsoup.connect(s).get();
                //System.out.println(doc);
                Element element = doc.selectFirst(".article");
                // System.out.println(element);
                String s1 = cleanHtml(element.html());
                contents.add(s1);
                //System.out.println(s1);
               // System.out.println("--------------------------------------------------------------------------");

            }

            for (int i = 0; i < urls.size(); i++) {
                News news1 = new News();
                news1.setTitle(titles.get(i));
                news1.setImageUrl(images.get(i));
                news1.setContent(contents.get(i));
                news1.setPublishTime(LocalDateTime.now());
                news1.setSource(urls.get(i));
                newsMapper.insertNews(news1);

            }

           // newsMapper.deleteNews();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String cleanHtml(String html) {
        Document doc = Jsoup.parse(html);
        // 移除不需要的样式和标签
        doc.select("style").remove();
        doc.select("script").remove();
        // 保留必要的样式和标签
        doc.select("[style*=text-align]").removeAttr("style");
        doc.select("[style*=text-indent]").removeAttr("style");
        doc.select("[style*=line-height]").removeAttr("style");
        doc.select("[style*=max-width]").removeAttr("style");
        doc.select("[style*=height]").removeAttr("style");
        doc.select("[style*=display]").removeAttr("style");
        doc.select("[style*=margin]").removeAttr("style");
        doc.select("[style*=padding]").removeAttr("style");
        doc.select("[style*=border]").removeAttr("style");
        doc.select("[style*=background]").removeAttr("style");
        doc.select("[style*=font]").removeAttr("style");
        doc.select("[style*=color]").removeAttr("style");
        doc.select("[style*=text-decoration]").removeAttr("style");
        doc.select("[style*=vertical-align]").removeAttr("style");
        doc.select("[style*=white-space]").removeAttr("style");
        doc.select("[style*=word-wrap]").removeAttr("style");
        doc.select("[style*=word-break]").removeAttr("style");
        doc.select("[style*=overflow]").removeAttr("style");
        doc.select("[style*=position]").removeAttr("style");
        doc.select("[style*=z-index]").removeAttr("style");
        doc.select("[style*=top]").removeAttr("style");
        doc.select("[style*=left]").removeAttr("style");
        doc.select("[style*=right]").removeAttr("style");
        doc.select("[style*=bottom]").removeAttr("style");
        doc.select("[style*=float]").removeAttr("style");
        doc.select("[style*=clear]").removeAttr("style");
        doc.select("[style*=list-style]").removeAttr("style");
        doc.select("[style*=list-style-type]").removeAttr("style");
        doc.select("[style*=list-style-position]").removeAttr("style");
        doc.select("[style*=list-style-image]").removeAttr("style");
        doc.select("[style*=list-style-indent]").removeAttr("style");
        doc.select("[style*=list-style-margin]").removeAttr("style");
        doc.select("[style*=list-style-padding]").removeAttr("style");
        doc.select("[style*=list-style-border]").removeAttr("style");
        doc.select("[style*=list-style-background]").removeAttr("style");
        doc.select("[style*=list-style-font]").removeAttr("style");
        doc.select("[style*=list-style-color]").removeAttr("style");
        doc.select("[style*=list-style-text-decoration]").removeAttr("style");
        doc.select("[style*=list-style-vertical-align]").removeAttr("style");
        doc.select("[style*=list-style-white-space]").removeAttr("style");
        doc.select("[style*=list-style-word-wrap]").removeAttr("style");
        doc.select("[style*=list-style-word-break]").removeAttr("style");
        doc.select("[style*=list-style-overflow]").removeAttr("style");
        doc.select("[style*=list-style-position]").removeAttr("style");
        doc.select("[style*=list-style-z-index]").removeAttr("style");
        doc.select("[style*=list-style-top]").removeAttr("style");
        doc.select("[style*=list-style-left]").removeAttr("style");
        doc.select("[style*=list-style-right]").removeAttr("style");
        doc.select("[style*=list-style-bottom]").removeAttr("style");
        doc.select("[style*=list-style-float]").removeAttr("style");
        doc.select("[style*=list-style-clear]").removeAttr("style");

        // 移除class和id属性
        doc.select("[class]").removeAttr("class");
        doc.select("[id]").removeAttr("id");

        // 将相对路径转换为绝对路径
        Elements imgElements = doc.select("img[src^=\"../../\"]");
        for (Element img : imgElements) {
            String src = img.attr("src");
            String newSrc = "https://www.caas.cn/" + src.substring(6); // 删除前缀 "../../"
            img.attr("src", newSrc);
        }

        return doc.body().html();
    }
}


